package com.yeyks.service.impl;

import com.google.common.collect.Lists;
import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.common.appcommon.dto.AppFileResult;
import com.yeyks.common.appcommon.result.CommonResult;
import com.yeyks.common.exception.OftenFiledException;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.commonReference.append.app.OssService;
import com.yeyks.service.AppFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class AppFileServiceImpl implements AppFileService {

    @Autowired
    private OssService ossService;

    @Override
    public CommonResult uploadFile(Boolean rdName, Boolean pubArea, MultipartFile file, AccountInfo accountInfo) {

        if (null != accountInfo) {
            Integer userId = accountInfo.getId();
            return ossUpload(userId, file, rdName, pubArea);
        }
        return CommonResult.failed("文件上传失败!");
    }

    @Override
    public CommonResult uploadFiles(Boolean rdName, Boolean pubArea, List<MultipartFile> files,
                                    AccountInfo accountInfo) {

        List<AppFileResult> fileResultList = Lists.newArrayList();
        if (null != accountInfo) {
            if (files != null && !files.isEmpty()) {
                for (MultipartFile file : files) {
                    CommonResult appFileResultCommonResult = ossUpload(accountInfo.getId(), file, rdName, pubArea);
                    if (null != appFileResultCommonResult && null != appFileResultCommonResult.getData()) {
                        fileResultList.add((AppFileResult) appFileResultCommonResult.getData());
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(fileResultList)) {
            return CommonResult.success(fileResultList);
        }
        return CommonResult.failed("批量上传文件失败");
    }

    @Override
    public CommonResult deleteFile(String absOssKey, AccountInfo accountInfo) {

        boolean flag = ossService.deleteOSS(absOssKey);
        if (flag) {
            return CommonResult.success(null, "删除文件成功");
        }
        return CommonResult.failed("删除文件失败");
    }

    /**
     * 文件上传调用
     *
     * @param userId  用户Id
     * @param file    文件
     * @param rdName  是否原名，不替代 “-”名称
     * @param pubArea 是否为公共文件 true --》 public
     * @return 返回结果
     */
    private CommonResult ossUpload(Integer userId, MultipartFile file, Boolean rdName, Boolean pubArea) {

        AppFileResult fileResult = new AppFileResult();
        if (!file.isEmpty()) {

            String filename = file.getOriginalFilename();

            if (rdName != null && rdName) {
                int posDot = filename.lastIndexOf('.');
                if (posDot == -1) {
                    filename = UUID.randomUUID().toString();
                } else {
                    String ext = filename.substring(posDot);
                    filename = UUID.randomUUID().toString() + ext;
                }
            } else {
                int posDot = filename.lastIndexOf('.');
                if (posDot == -1) {
                    filename = UUID.randomUUID().toString();
                } else {
                    String ext = filename.substring(posDot);
                    filename = UUID.randomUUID().toString().replaceAll("-", "") + ext;
                }
            }

            String ossKey;
            if (pubArea != null && pubArea) {
                ossKey = "Public/" + filename;
            } else {
                ossKey = "User/" + userId.toString() + "/" + filename;
            }

            try {
                if (ossService.writeOSS(file.getBytes(), ossKey)) {
                    fileResult.setFilename(filename);
                    fileResult.setAbsOssKey(ossKey);
                    fileResult.setUrl(ossService.getPrefixUrl() + ossKey);

                    return CommonResult.success(fileResult);
                } else {
                    return CommonResult.failed("上传失败");
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new OftenFiledException("文件上传异常");
            }
        } else {
            throw new ServiceException("权限不足");
        }
    }
}
